import { getToken, setToken, removeToken, settimestamp } from '@/utils/auth'
import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { resetRouter } from '@/router'
// import Vue from 'vue'
const state = {
  token: getToken(),
  userinfo: {}// 客户信息

}
// 修改状态
const mutations = {
  // 更新token
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  // 删除token
  removeToken() {
    state.token = ''
    removeToken()
  },
  // 修改用户信息
  setuserinfo(state, result) {
    state.userinfo = result
  },
  // 删除用户信息
  reomveUserInfo(state) {
    state.userinfo = {}
  }
}
// 异步执行
const actions = {
  // 登陆
  async login(context, data) {
    const token = await login(data)
    settimestamp()
    context.commit('setToken', token)
  },

  // 获取客户信息
  async getUserInfo(context) {
    const result = await getUserInfo()
    const baseInfo = await getUserDetailById(result.userId) // 为了获取头像
    const baseuser = { ...result, ...baseInfo }
    context.commit('setuserinfo', baseuser)
    return baseuser
  },

  // 登出页面
  logout(context) {
    context.commit('removeToken') // 删除token
    context.commit('reomveUserInfo')// 删除用户信息
    resetRouter()// 重置路由addRoutes
    context.commit('permission/setRoutes', [], { root: true })// 重置vuex里面的routes
  }

}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

